package com.lalawaimai.palteform.baselib.http;

import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;

/**
 * client类封装
 * Created by WaterWood on 2018/5/29.
 */
public class CommonOkHttpClient {
    private static final int TIME_OUT = 30;//超时参数
    private static OkHttpClient mOkHttpClient;

    //为我们的Client去配置参数
    static {
        //创建我们client对象的构建者
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
        //为构建者填充超时时间
        okHttpBuilder.connectTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpBuilder.readTimeout(TIME_OUT, TimeUnit.SECONDS);
        okHttpBuilder.writeTimeout(TIME_OUT, TimeUnit.SECONDS);
        //设置允许重定向
        okHttpBuilder.followRedirects(true);
        //https支持
        okHttpBuilder.hostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        okHttpBuilder.sslSocketFactory(HttpUtils.getSslSocketFactory());
        mOkHttpClient = okHttpBuilder.build();
    }

    /**
     * 发送请求
     * @param request 请求参数封装，使用CommonRequest
     * @param commonCallback 请求回调
     * @return
     */
    public static Call sendRequest(Request request, CommonJsonCallback commonCallback){
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(commonCallback);
        return call;
    }
}
